﻿using msBsc.AppLogic.DataAlc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace msBsc.WebUi.ShpMana
{
    public partial class wfRegionalAgentList : msBsc.Cls.BPageHt
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private void BindControls()
        {
            if (!IsPostBack)
            {
            }
        }

        //重构基类的回调处理函数，以strAction属性来判断是什么类型的回调，该变量的值对应前台的ACTION参数，如：按钮的名称等
        public override void InitialByParam()
        {
            if (this.gtGridRet != null)
            {
                if (this.gtGridRet.action == "load" || this.gtGridRet.action == "export")//处理GRID的数据原获取和数据导出
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    if (ds != null && ds.Tables.Count > 0)
                        SetReturnDatatable(ds.Tables[0], "OFFICIAL_NEWS_ID");//BANK_ID为表的KEY字段，可填可不填
                }
                //处理数据保存
                if (this.gtGridRet.action == "save" && (gtGridRet.insertedRecords.Length > 0 || gtGridRet.updatedRecords.Length > 0 || gtGridRet.deletedRecords.Length > 0))
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    try
                    {
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            ////处理记录新增，前台已传入新增的ROW
                            //for (int i = 0; i < gtGridRet.insertedRecords.Length; i++)
                            //{
                            //    DataRow drNew = ds.Tables[0].NewRow();
                            //    drNew["OFFICIAL_NEWS_TITLE"] = gtGridRet.insertedRecords[i]["OFFICIAL_NEWS_TITLE"];
                            //    drNew["OFFICIAL_NEWS_CONTENT"] = gtGridRet.insertedRecords[i]["OFFICIAL_NEWS_CONTENT"];
                            //    drNew["NEWS_PUBLISH_TIME"] = gtGridRet.insertedRecords[i]["NEWS_PUBLISH_TIME"];
                            //    drNew["NEWS_EXPIRA_TIME"] = gtGridRet.insertedRecords[i]["NEWS_EXPIRA_TIME"];
                            //    drNew["NEWS_PUBLISH_BY"] = msBsc.SvRef.UserInfo.Operator;
                            //    drNew["OFFICIAL_NEWS_ID"] = new Epm.AppLogic.Framework.CDbAccess().NewID();
                            //    drNew["NEWS_IS_DELETED"] = 0;
                            //    drNew["NEWS_IS_DISPLAY"] = 1;
                            //    ds.Tables[0].Rows.Add(drNew);
                            //}

                            //处理记录更新，前台已传入更新的ROW
                            //for (int i = 0; i < gtGridRet.updatedRecords.Length; i++)
                            //{
                            //    string stridtm = gtGridRet.updatedRecords[i]["OFFICIAL_NEWS_ID"].ToString();
                            //    if (stridtm != string.Empty)
                            //    {
                            //        for (int j = ds.Tables[0].Rows.Count - 1; j >= 0; j--)
                            //        {
                            //            if (ds.Tables[0].Rows[j]["OFFICIAL_NEWS_ID"].ToString() == stridtm)
                            //            {
                            //                ds.Tables[0].Rows[j]["OFFICIAL_NEWS_TITLE"] = gtGridRet.updatedRecords[i]["OFFICIAL_NEWS_TITLE"];
                            //                ds.Tables[0].Rows[j]["OFFICIAL_NEWS_CONTENT"] = gtGridRet.updatedRecords[i]["OFFICIAL_NEWS_CONTENT"];
                            //                ds.Tables[0].Rows[j]["NEWS_PUBLISH_TIME"] = gtGridRet.updatedRecords[i]["NEWS_PUBLISH_TIME"];
                            //                ds.Tables[0].Rows[j]["NEWS_EXPIRA_TIME"] = gtGridRet.updatedRecords[i]["NEWS_EXPIRA_TIME"];
                            //                ds.Tables[0].Rows[j]["NEWS_IS_DELETED"] = gtGridRet.updatedRecords[i]["NEWS_IS_DELETED"];
                            //            }
                            //        }
                            //    }
                            //}
                            //删除
                            //for (int i = 0; i < gtGridRet.deletedRecords.Length; i++)
                            //{
                            //    string stridtm = gtGridRet.deletedRecords[i]["OFFICIAL_NEWS_ID"].ToString();
                            //    if (stridtm != string.Empty)
                            //    {
                            //        DataRow[] arrtemr = ds.Tables[0].Select("OFFICIAL_NEWS_ID='" + stridtm + "'");
                            //        if (arrtemr.Length > 0)
                            //        {
                            //            arrtemr[0]["NEWS_IS_DELETED"] = 1;
                            //        }
                            //    }
                            //}
                            if (ds.HasChanges())
                            {
                                System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                                transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                                transactionOption.Timeout = new TimeSpan(0, 10, 0);
                                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                                {
                                    using (msBsc.AppLogic.DataAlc.CBizOfficialNews objCBizOfficialNews = new CBizOfficialNews())
                                    {
                                        objCBizOfficialNews.Update(ds);
                                        ds.AcceptChanges();
                                    }
                                    ts.Complete();
                                    ts.Dispose();
                                    //msBsc.AppLogic.Cfg.SystemSet.oSystemSet.initdicDataSysSet();
                                }
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        ds.RejectChanges();
                        gtGridRetSaveException = err.Message;
                    }
                }
                if (gtGridRetSaveSuccess && (this.gtGridRet.action == "save" || strAction == "btnSave"))//根据传入的回调类型进行处理，这里响应编辑按钮
                {
                    //保存后将页面置为查看状态
                    SetMode("VIEW");
                }
            }
            else if (strAction == "btnEdit")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("EDIT");
            }
            else if (strAction == "btnNotSave")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("VIEW");
            }
            else if (strAction == "btnConfirm")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "True");
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnCancel")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "False");
                this.ExecJScript("btnDo('mFinder');");
            }

            base.InitialByParam();
        }

        private void SetItemStatus(string strIds, string strStatus)
        {
            using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
            {
                DataSet ds = oCDbAccess.QueryBySQL("SELECT * FROM BSE_BANK WHERE BANK_ID IN ('" + strIds.Replace(",", "','") + "')");
                ds.Tables[0].TableName = "BSE_BANK";

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["REC_ACTIVE"].ToString() != strStatus)
                    {
                        ds.Tables[0].Rows[i]["REC_ACTIVE"] = strStatus == "True";
                    }
                }
                if (ds.HasChanges())
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        using (Epm.AppLogic.Framework.CustBizObject objtem1 = new Epm.AppLogic.Framework.CustBizObject(ds.Tables[0], "", "BANK_ID"))
                        {
                            objtem1.Update(ds);
                        }
                        ds.AcceptChanges();

                        ts.Complete();
                        ts.Dispose();
                        //msBsc.SvRef.ApplicationConst.Const.DataConst = null;
                    }
                }
            }
        }

        //修改页面状态
        private void SetMode(string strMode)
        {
            EditMode = strMode; switch (strMode)
            {
                case "EDIT":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", true);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "ADD":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "VIEW":
                    EnabledLinkBtn("btnEdit", true);
                    EnabledLinkBtn("btnSave", false);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", true);
                    EnabledLinkBtn("btnCancel", true);
                    this.ExecJScript("doCancelGt('myGrid1');");
                    break;
            }
        }

        //获取数据原,"DP_DATA"字符一定不要改变，否则系统不能自动清除缓存
        public DataSet GetDisplayData(string strgtGridID, string strSrcF, string strsRadom)
        {
            if (strgtGridID == "myGrid1")
            {
                DataSet ds;
                //点击查询按钮时，或需要数据而没有缓存时，根据条件取出数据记录
                if (strSrcF == "mFinder" || !this.SessionIsExists(strsRadom + "DP_DATA", "1"))
                {
                    string queryStr = string.Empty;
                    //姓名 电话
                    string realName = this.GetParamHtValue("txtRealName");

                    if (!string.IsNullOrEmpty(realName))
                    {
                        queryStr += " AND B.CUSTOMER_BASEINFO_NAME LIKE '%" + realName + "%' ";
                    }
                    string mobile = this.GetParamHtValue("txtMobile");
                    if (!string.IsNullOrEmpty(mobile))
                    {
                        queryStr += " AND B.CUSTOMER_BASEINFO_MOBILE='" + mobile + "'";
                    }
                    //地区
                    string countryId = this.GetParamHtValue("countryId");
                    if (!string.IsNullOrEmpty(countryId) && countryId!="0")
                    {
                        queryStr += " AND B.AGENT_COUNTRY_ID='" + countryId + "'";
                    }
                    string cityId = this.GetParamHtValue("cityId");
                    if (!string.IsNullOrEmpty(cityId) && cityId!="0")
                    {
                        queryStr += " AND B.AGENT_CITY_ID='" + cityId + "'";
                    }
                    string destinationId = this.GetParamHtValue("destinationId");
                    if (!string.IsNullOrEmpty(destinationId) && destinationId!="0")
                    {
                        queryStr += " AND B.AGENT_DISTINATION_ID='" + destinationId + "'";
                    }

                    using (msBsc.AppLogic.DataAlc.CBizCustomerBaseInfo objCBizBaseInfo = new CBizCustomerBaseInfo())
                    {
                        ds = objCBizBaseInfo.DataObj.QueryBySQL(@"SELECT T.*,B.COUNTRY_CITY_NME C_NAME,C.COUNTRY_CITY_NME P_NAME,D.COUNTRY_CITY_NME A_NAME FROM 
(SELECT R.CUSTOMER_REGISTER_ID,R.CUSTOMER_DEFAULT_PIC,B.CUSTOMER_BASEINFO_NAME,
B.CUSTOMER_BASEINFO_GENDER,B.CUSTOMER_CREDENTIALS_TYPE,
B.CUSTOMER_CREDENTIALS_NO,B.CUSTOMER_BASEINFO_BIRTH,B.CUSTOMER_BASEINFO_PHONE,
B.CUSTOMER_BASEINFO_MOBILE,B.CUSTOMER_BASEINFO_QQ,B.CUSTOMER_WECHAT_NO,B.CUSTOMER_BANK_ACCOUNT,
B.CUSTOMER_BANK_TYPE,B.DOCUMENT_IMAGE,
B.AGENT_DISTINATION_ID,
B.AGENT_CITY_ID,B.AGENT_COUNTRY_ID,R.ACCOUNT_IS_DELETED 
 FROM DJK_CUSTOMER_REGISTER(NOLOCK) R  
LEFT JOIN DJK_CUSTOMER_BASEINFO(NOLOCK) B
ON R.CUSTOMER_REGISTER_ID=B.CUSTOMER_BASEINFO_ID WHERE R.CUSTOMER_ACCOUNT_TYPE=5 " + queryStr + @") T 
LEFT JOIN DJK_COUNTRY_CITY B ON T.AGENT_COUNTRY_ID=B.COUNTRY_CITY_ID
LEFT JOIN DJK_COUNTRY_CITY C ON T.AGENT_CITY_ID=C.COUNTRY_CITY_ID
LEFT JOIN DJK_COUNTRY_CITY D ON T.AGENT_DISTINATION_ID=D.COUNTRY_CITY_ID");


                        ds.AcceptChanges();
                        SetSession(strsRadom + "DP_DATA", ds, "1");
                        //查询时，将页面置为查看状态
                        if (strSrcF == "mFinder")
                            SetMode("VIEW");
                    }
                }
                else
                {
                    ds = (DataSet)this.GetSession(strsRadom + "DP_DATA", "1");
                }
                return ds;
            }
            else
            {
                return null;
            }
        }

        public override void DoAction()
        {
            if (this.strAction == "changeArea")
            {
                RefreshArea();
            }
            else if (this.strAction=="upStatus")
            {
                //启用、禁用
                updateStatus();
            }
        }
        /// <summary>
        /// 启用禁用 数据
        /// </summary>
        public void updateStatus() {
            string userid = this.GetParamHtValue("userid");
            string status = this.GetParamHtValue("status");
            if (string.IsNullOrEmpty(status)||string.IsNullOrEmpty(userid))
            {
                this.ExecJScript("参数错误，请重试"); return;
            }
            using (CBizCustomerRegister register=new CBizCustomerRegister ())
            {
                string[] message= register.UpdateStatus(userid, 5,Convert.ToInt16(status));
                if (Convert.ToBoolean(message[0]))
                {
                    this.ExecJScript("success();"); return;
                }

                this.ExecJScript(message[1]);
            }


        }
       
        /// <summary>
        /// 地区联动
        /// </summary>
        private void RefreshArea()
        {
            string countryId = this.GetParamHtValue("countryId");
            string cityId = this.GetParamHtValue("cityId");

            DataSet ds1, ds2;

            using (msBsc.AppLogic.DataAlc.CBizCountryCity objCBizCountryCity = new AppLogic.DataAlc.CBizCountryCity())
            {
                ds1 = string.IsNullOrEmpty(countryId) ? null : objCBizCountryCity.SelectCountryByParentId(countryId);

                ds2 = string.IsNullOrEmpty(cityId) ? null : objCBizCountryCity.SelectCountryByParentId(cityId);
            }

            if (ds1 != null)
            {
                var countryJson = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(ds1.Tables[0], "", "", 1, 200, "");
                this.ExecJScript(@"var _html = $('#country_city_list').html();
                            laytpl(_html).render(" + countryJson + @", function (render) {
                                $('#selCity').html(render);
                            });");
            }

            if (ds2 != null)
            {
                var cityJson = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(ds2.Tables[0], "", "", 1, 200, "");
                this.ExecJScript(@"var _html = $('#city_des_list').html();
                            laytpl(_html).render(" + cityJson + @", function (render) {
                                $('#selDestination').html(render);
                            });");
            }
        }

    }
}